package xorm

import (
	"context"
	"database/sql"
	"errors"
	"fmt"
	"gitee.com/KotlinToGo/xorm/core"
	"gitee.com/KotlinToGo/xorm/dialect"
	"gitee.com/KotlinToGo/xorm/ictx"
	"gitee.com/KotlinToGo/xorm/internal/utils"
	"gitee.com/KotlinToGo/xorm/log"
	"gitee.com/KotlinToGo/xorm/mapper"
	"gitee.com/KotlinToGo/xorm/schema"
	"github.com/fsnotify/fsnotify"
	"io"
	"os"
	"reflect"
	"strconv"
	"strings"
	"sync"
	"time"
)

var o sync.Once

// Engine 是orm的主要结构，表示数据库管理器.通常，一个应用程序只需要一个引擎。
type Engine struct {
	db         *core.DB
	dialect    dialect.IDialect   // 主要是为了传给 Session.statement
	tagParser  *dialect.Parser    // 主要是为了传给 Session.statement
	DatabaseTZ *time.Location     // 主要是为了传给 Session.statement (数据库的时区)
	TZLocation *time.Location     // 应用程序的时区
	cache      *schema.Manager    // 缓存模块
	ctx        context.Context    // 默认上下文。
	logger     log.IContextLogger // 上下文日志模块。

	group  *EngineGroup
	driver       string //驱动名称，例如:"mysql","mssql",...
	dsn          string //对应驱动的 dataSourceName 连接信息
	SqlMap       SqlMap
	SqlTemplate  ISqlTemplate // 代码位于 7_xorm_util_sql_template.go
	watcher      *fsnotify.Watcher
	logSessionID bool // 默认为false,表示:没有创建 Session对象。初始化一个 Engine 对象时不会自动创建 Session 对象。
}


// DB 返回一个 Engine 持有的 *core.DB 对象。
func (e *Engine) DB() *core.DB {
	return e.db
}

// SetSessionID (EnableSessionID) 是否启用会话ID。
func (e *Engine) SetSessionID(enable bool) {
	e.logSessionID = enable
}

// SetICache (SetCacher) 设置表的缓存器
func (e *Engine) SetICache(tableName string, cacher schema.ICache) {
	e.cache.SetICache(tableName, cacher)
}

// GetICache (GetCacher) 返回指定表的缓存器。
func (e *Engine) GetICache(tableName string) schema.ICache {
	return e.cache.GetICache(tableName)
}

// SetQuotePolicy sets the special quote policy
func (e *Engine) SetQuotePolicy(quotePolicy dialect.QuotePolicy) {
	e.dialect.SetQuotePolicy(quotePolicy)
}

// SetBufferSize (BufferSize) 设置要迭代的缓冲区大小
func (e *Engine) SetBufSize(size int) *Session {
	session := e.NewSession()
	session.autoClose = true
	return session.SetBufSize(size)
}

// ShowSQL 如果日志级别大于INFO，则在记录器上显示或不显示SQL语句。
func (e *Engine) ShowSQL(show ...bool) {
	e.logger.ShowSQL(show...)
	e.DB().Logger = e.logger
}

// Logger 返回日志记录器接口
func (e *Engine) Logger() log.IContextLogger {
	return e.logger
}

// SetLogger 设置新的日志记录器。
func (e *Engine) SetLogger(logger interface{}) {
	var l log.IContextLogger
	switch t := logger.(type) {
	case log.IContextLogger:
		l = t
	case log.ILogger:
		l = log.NewLoggerAdapter(t)
	}
	e.logger = l
	e.DB().Logger = l
}

// SetLogLevel 设置记录器级别.
func (e *Engine) SetLogLevel(level log.LoggerLevel) {
	e.logger.SetLevel(level)
}

// SetDisableGlobalCache 是否禁用全局缓存。
func (e *Engine) SetDisableGlobalCache(disable bool) {
	e.cache.SetDisableGlobalCache(disable)
}

// GetDriver (DriverName) 返回当前sql驱动程序的名称。
func (e *Engine) GetDriver() string {
	return e.driver
}

// GetDSN (DataSourceName) 返回当前的连接字符串。
func (e *Engine) GetDSN() string {
	return e.dsn
}

// SetMapper set the name mapping rules
func (e *Engine) SetMapper(mapper mapper.IMapper) {
	e.SetTableMapper(mapper)
	e.SetColumnMapper(mapper)
}

// SetTableMapper set the table name mapping rule
func (e *Engine) SetTableMapper(mapper mapper.IMapper) {
	e.tagParser.SetTableMapper(mapper)
}

// SetColumnMapper set the column name mapping rule
func (e *Engine) SetColumnMapper(mapper mapper.IMapper) {
	e.tagParser.SetColumnMapper(mapper)
}

// Quote Use QuoteStr quote the string sql
func (e *Engine) Quote(value string) string {
	value = strings.TrimSpace(value)
	if len(value) == 0 {
		return value
	}

	buf := strings.Builder{}
	e.QuoteTo(&buf, value)

	return buf.String()
}

// QuoteTo quotes string and writes into the buffer
func (e *Engine) QuoteTo(buf *strings.Builder, value string) {
	if buf == nil {
		return
	}

	value = strings.TrimSpace(value)
	if value == "" {
		return
	}
	e.dialect.Quoter().QuoteTo(buf, value)
}

// SQLType 方言的 core.SqlType 方法的简单包装。
func (e *Engine) SQLType(c *schema.Column) string {
	return e.dialect.SQLType(c)
}

// AutoIncrStr 数据库自动增量语句。
func (e *Engine) AutoIncrStr() string {
	return e.dialect.AutoIncrStr()
}

// SetConnMaxLifetime 设置连接可以重用的最长时间。
func (e *Engine) SetConnMaxLifetime(d time.Duration) {
	e.DB().SetConnMaxLifetime(d)
}

// SetMaxOpenConns is only available for go 1.2+
func (e *Engine) SetMaxOpenConns(conns int) {
	e.DB().SetMaxOpenConns(conns)
}

// SetMaxIdleConns set the max idle connections on pool, default is 2
func (e *Engine) SetMaxIdleConns(conns int) {
	e.DB().SetMaxIdleConns(conns)
}

// SetDefaultCacher set the default cacher. Xorm's default not enable cacher.
func (e *Engine) SetDefaultICache(cacher schema.ICache) {
	e.cache.SetDefaultICache(cacher)
}

// GetDefaultCacher returns the default cacher
func (e *Engine) GetDefaultICache() schema.ICache {
	return e.cache.GetDefaultICache()
}

// NoCache If you has set default cacher, and you want temporilly stop use cache,
// you can use NoCache()
func (e *Engine) NoCache() *Session {
	session := e.NewSession()
	session.autoClose = true
	return session.NoCache()
}

// NoCascade If you do not want to auto cascade load object
func (e *Engine) NoCascade() *Session {
	session := e.NewSession()
	session.autoClose = true
	return session.NoCascade()
}

// MapCacher Set a table use a special cacher
func (e *Engine) MapICache(bean interface{}, cacher schema.ICache) error {
	e.SetICache(dialect.FullTableName(e.dialect, e.GetTableMapper(), bean, true), cacher)
	return nil
}

// NewDB 返回一个新的 *core.DB 对象，这个对象不是 Engine 的成员(db)
func (e *Engine) NewDB() (*core.DB, error) {
	return core.Open(e.driver, e.dsn)
}


// Dialect return database dialect
func (e *Engine) Dialect() dialect.IDialect {
	return e.dialect
}

// NewSession New a session
func (e *Engine) NewSession() *Session {
	return newSession(e)
}

// Close 关闭 Engine 的数据库连接。
func (e *Engine) Close() error {
	return e.DB().Close()
}

// Ping tests if database is alive
func (e *Engine) Ping() error {
	s := e.NewSession()
	defer s.Close()
	return s.Ping()
}

// SQL 让我们手动编写原始SQL并进行操作。
//
// For example:
//  engine.SQL("select * from user").Find(&users)
//	此代码将执行 "select * from user" 并将记录设置为用户。
func (e *Engine) Sql(query interface{}, args ...interface{}) *Session {
	session := e.NewSession()
	session.autoClose = true
	switch query.(type) {
	case string:
		session.isSqlFunc = true
	default:
		session.isSqlFunc = false
	}
	return session.Sql(query, args...)
}

// NoAutoTime Default if your struct has "created" or "updated" filed tag, the fields
// will automatically be filled with current time when Insert or Update
// invoked. Call NoAutoTime if you dont' want to fill automatically.
func (e *Engine) NoAutoTime() *Session {
	session := e.NewSession()
	session.autoClose = true
	return session.NoAutoTime()
}

// NoAutoCondition disable auto generate Where condition from bean or not
func (e *Engine) NoAutoCondition(no ...bool) *Session {
	session := e.NewSession()
	session.autoClose = true
	return session.NoAutoCondition(no...)
}

func (e *Engine) loadTableInfo(table *schema.Table) error {
	colSeq, cols, err := e.dialect.GetColumns(e.db, e.ctx, table.Name)
	if err != nil {
		return err
	}
	for _, name := range colSeq {
		table.AddColumn(cols[name])
	}
	indexes, err := e.dialect.GetIndexes(e.db, e.ctx, table.Name)
	if err != nil {
		return err
	}
	table.Indexes = indexes

	var seq int
	for _, index := range indexes {
		for _, name := range index.Cols {
			parts := strings.Split(name, " ")
			if len(parts) > 1 {
				if parts[1] == "DESC" {
					seq = 1
				}
			}
			if col := table.GetColumn(parts[0]); col != nil {
				col.Indexes[index.Name] = index.Type
			} else {
				return fmt.Errorf("Unknown col %s seq %d, in index %v of table %v, columns %v", name, seq, index.Name, table.Name, table.ColumnsSeq())
			}
		}
	}
	return nil
}
//
// GetDBMeta (DBMetas) 获取到数据库中所有的表，字段，索引的信息。
func (e *Engine) GetDBMeta() ([]*schema.Table, error) {
	tables, err := e.dialect.GetTables(e.db, e.ctx)
	if err != nil {
		return nil, err
	}

	for _, table := range tables {
		if err = e.loadTableInfo(table); err != nil {
			return nil, err
		}
	}
	return tables, nil
}

// DumpAllToFile dump database all table structs and data to a file
func (e *Engine) DumpAllToFile(fp string, tp ...schema.DBType) error {
	f, err := os.Create(fp)
	if err != nil {
		return err
	}
	defer f.Close()
	return e.DumpAll(f, tp...)
}

// DumpAll dump database all table structs and data to w
func (e *Engine) DumpAll(w io.Writer, tp ...schema.DBType) error {
	tables, err := e.GetDBMeta()
	if err != nil {
		return err
	}
	return e.DumpTables(tables, w, tp...)
}

// DumpTablesToFile dump specified tables to SQL file.
func (e *Engine) DumpTablesToFile(tables []*schema.Table, fp string, tp ...schema.DBType) error {
	f, err := os.Create(fp)
	if err != nil {
		return err
	}
	defer f.Close()
	return e.DumpTables(tables, f, tp...)
}

// DumpTables dump specify tables to io.Writer
func (e *Engine) DumpTables(tables []*schema.Table, w io.Writer, tp ...schema.DBType) error {
	return e.dumpTables(tables, w, tp...)
}

func formatColumnValue(dstDialect dialect.IDialect, d interface{}, col *schema.Column) string {
	if d == nil {
		return "NULL"
	}

	if dq, ok := d.(bool); ok && (dstDialect.URI().DBType == schema.Sqlite ||
		dstDialect.URI().DBType == schema.Mssql) {
		if dq {
			return "1"
		}
		return "0"
	}

	if col.SQLType.IsText() {
		var v = fmt.Sprintf("%s", d)
		return "'" + strings.Replace(v, "'", "''", -1) + "'"
	} else if col.SQLType.IsTime() {
		var v = fmt.Sprintf("%s", d)
		if strings.HasSuffix(v, " +0000 UTC") {
			return fmt.Sprintf("'%s'", v[0:len(v)-len(" +0000 UTC")])
		} else if strings.HasSuffix(v, " +0000 +0000") {
			return fmt.Sprintf("'%s'", v[0:len(v)-len(" +0000 +0000")])
		}
		return "'" + strings.Replace(v, "'", "''", -1) + "'"
	} else if col.SQLType.IsBlob() {
		if reflect.TypeOf(d).Kind() == reflect.Slice {
			return fmt.Sprintf("%s", dstDialect.FormatBytes(d.([]byte)))
		} else if reflect.TypeOf(d).Kind() == reflect.String {
			return fmt.Sprintf("'%s'", d.(string))
		}
	} else if col.SQLType.IsNumeric() {
		switch reflect.TypeOf(d).Kind() {
		case reflect.Slice:
			if col.SQLType.Name == schema.Bool {
				return fmt.Sprintf("%v", strconv.FormatBool(d.([]byte)[0] != byte('0')))
			}
			return fmt.Sprintf("%s", string(d.([]byte)))
		case reflect.Int16, reflect.Int8, reflect.Int32, reflect.Int64, reflect.Int:
			if col.SQLType.Name == schema.Bool {
				v := reflect.ValueOf(d).Int() > 0
				if dstDialect.URI().DBType == schema.Sqlite {
					if v {
						return "1"
					}
					return "0"
				}
				return fmt.Sprintf("%v", strconv.FormatBool(v))
			}
			return fmt.Sprintf("%v", d)
		case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
			if col.SQLType.Name == schema.Bool {
				v := reflect.ValueOf(d).Uint() > 0
				if dstDialect.URI().DBType == schema.Sqlite {
					if v {
						return "1"
					}
					return "0"
				}
				return fmt.Sprintf("%v", strconv.FormatBool(v))
			}
			return fmt.Sprintf("%v", d)
		default:
			return fmt.Sprintf("%v", d)
		}
	}

	s := fmt.Sprintf("%v", d)
	if strings.Contains(s, ":") || strings.Contains(s, "-") {
		if strings.HasSuffix(s, " +0000 UTC") {
			return fmt.Sprintf("'%s'", s[0:len(s)-len(" +0000 UTC")])
		}
		return fmt.Sprintf("'%s'", s)
	}
	return s
}

// dumpTables dump database all table structs and data to w with specify db type
func (e *Engine) dumpTables(tables []*schema.Table, w io.Writer, tp ...schema.DBType) error {
	var d dialect.IDialect
	if len(tp) == 0 {
		d = e.dialect
	} else {
		d = dialect.QueryDialect(tp[0])
		if d == nil {
			return errors.New("Unsupported database type")
		}

		uri := e.dialect.URI()
		destURI := dialect.URI{
			DBType: tp[0],
			DBName: uri.DBName,
		}
		d.Init(&destURI)
	}

	_, err := io.WriteString(w, fmt.Sprintf("/*Generated by xorm %s, from %s to %s*/\n\n",
		time.Now().In(e.TZLocation).Format("2006-01-02 15:04:05"), e.dialect.URI().DBType, d.URI().DBType))
	if err != nil {
		return err
	}

	for i, table := range tables {
		tableName := table.Name
		if d.URI().Schema != "" {
			tableName = fmt.Sprintf("%s.%s", d.URI().Schema, table.Name)
		}
		or := table.Name
		if e.dialect.URI().Schema != "" {
			or = fmt.Sprintf("%s.%s", e.dialect.URI().Schema, table.Name)
		}
		if i > 0 {
			_, err = io.WriteString(w, "\n")
			if err != nil {
				return err
			}
		}
		sqls, _ := d.CreateTableSQL(table, tableName)
		for _, s := range sqls {
			_, err = io.WriteString(w, s+";\n")
			if err != nil {
				return err
			}
		}
		if len(table.PKColumns()) > 0 && d.URI().DBType == schema.Mssql {
			fmt.Fprintf(w, "SET IDENTITY_INSERT [%s] ON;\n", table.Name)
		}

		for _, index := range table.Indexes {
			_, err = io.WriteString(w, d.CreateIndexSQL(table.Name, index)+";\n")
			if err != nil {
				return err
			}
		}

		cols := table.ColumnsSeq()
		colNames := e.dialect.Quoter().Join(cols, ", ")
		destColNames := d.Quoter().Join(cols, ", ")

		rows, err := e.DB().QueryContext(e.ctx, "SELECT "+colNames+" FROM "+e.Quote(or))
		if err != nil {
			return err
		}
		defer rows.Close()

		for rows.Next() {
			dest := make([]interface{}, len(cols))
			err = rows.ScanSlice(&dest)
			if err != nil {
				return err
			}

			_, err = io.WriteString(w, "INSERT INTO "+d.Quoter().Quote(tableName)+" ("+destColNames+") VALUES (")
			if err != nil {
				return err
			}

			var temp string
			for i, de := range dest {
				col := table.GetColumn(cols[i])
				if col == nil {
					return errors.New("unknow column error")
				}
				temp += "," + formatColumnValue(d, de, col)
			}
			_, err = io.WriteString(w, temp[1:]+");\n")
			if err != nil {
				return err
			}
		}

		// FIXME: Hack for postgres
		if d.URI().DBType == schema.Postgres && table.AutoIncrColumn() != nil {
			_, err = io.WriteString(w, "SELECT setval('"+tableName+"_id_seq', COALESCE((SELECT MAX("+table.AutoIncrColumn().Name+") + 1 FROM "+d.Quoter().Quote(tableName)+"), 1), false);\n")
			if err != nil {
				return err
			}
		}
	}
	return nil
}

// Cascade use cascade or not
func (e *Engine) Cascade(trueOrFalse ...bool) *Session {
	s := e.NewSession()
	s.autoClose = true
	return s.Cascade(trueOrFalse...)
}

// Where method provide a condition query
func (e *Engine) Where(query interface{}, args ...interface{}) *Session {
	s := e.NewSession()
	s.autoClose = true
	return s.Where(query, args...)
}

// ID method provoide a condition as (id) = ?
func (e *Engine) Id(id interface{}) *Session {
	s := e.NewSession()
	s.autoClose = true
	return s.Id(id)
}

// Before apply before Processor, affected bean is passed to closure arg
func (e *Engine) Before(closures func(interface{})) *Session {
	s := e.NewSession()
	s.autoClose = true
	return s.Before(closures)
}

// After apply after insert Processor, affected bean is passed to closure arg
func (e *Engine) After(closures func(interface{})) *Session {
	s := e.NewSession()
	s.autoClose = true
	return s.After(closures)
}

// Charset set charset when create table, only support mysql now
func (e *Engine) Charset(charset string) *Session {
	s := e.NewSession()
	s.autoClose = true
	return s.Charset(charset)
}

// StoreEngine set store engine when create table, only support mysql now
func (e *Engine) StoreEngine(storeEngine string) *Session {
	s := e.NewSession()
	s.autoClose = true
	return s.StoreEngine(storeEngine)
}

// Distinct use for distinct columns. Caution: when you are using cache,
// distinct will not be cached because cache system need id,
// but distinct will not provide id
func (e *Engine) Distinct(columns ...string) *Session {
	s := e.NewSession()
	s.autoClose = true
	return s.Distinct(columns...)
}

// Select customerize your select columns or contents
func (e *Engine) Select(str string) *Session {
	s := e.NewSession()
	s.autoClose = true
	return s.Select(str)
}

// Cols only use the parameters as select or update columns
func (e *Engine) Field(columns ...string) *Session {
	s := e.NewSession()
	s.autoClose = true
	return s.Field(columns...)
}

// AllCols indicates that all columns should be use
func (e *Engine) AllCols() *Session {
	s := e.NewSession()
	s.autoClose = true
	return s.AllCols()
}

// MustCols specify some columns must use even if they are empty
func (e *Engine) MustField(columns ...string) *Session {
	s := e.NewSession()
	s.autoClose = true
	return s.MustField(columns...)
}

// UseBool xorm automatically retrieve condition according struct, but
// if struct has bool field, it will ignore them. So use UseBool
// to tell system to do not ignore them.
// If no parameters, it will use all the bool field of struct, or
// it will use parameters's columns
func (e *Engine) UseBool(columns ...string) *Session {
	s := e.NewSession()
	s.autoClose = true
	return s.UseBool(columns...)
}

// Omit only not use the parameters as select or update columns
func (e *Engine) Omit(columns ...string) *Session {
	s := e.NewSession()
	s.autoClose = true
	return s.Omit(columns...)
}

// Nullable set null when column is zero-value and nullable for update
func (e *Engine) Nullable(columns ...string) *Session {
	s := e.NewSession()
	s.autoClose = true
	return s.Nullable(columns...)
}

// In will generate "column IN (?, ?)"
func (e *Engine) In(column string, args ...interface{}) *Session {
	s := e.NewSession()
	s.autoClose = true
	return s.In(column, args...)
}

// NotIn will generate "column NOT IN (?, ?)"
func (e *Engine) NotIn(column string, args ...interface{}) *Session {
	s := e.NewSession()
	s.autoClose = true
	return s.NotIn(column, args...)
}

// Incr provides a update string like "column = column + ?"
func (e *Engine) Incr(column string, args ...interface{}) *Session {
	s := e.NewSession()
	s.autoClose = true
	return s.Incr(column, args...)
}

// Decr provides a update string like "column = column - ?"
func (e *Engine) Decr(column string, args ...interface{}) *Session {
	s := e.NewSession()
	s.autoClose = true
	return s.Decr(column, args...)
}

// SetExpr provides a update string like "column = {expression}"
func (e *Engine) SetExpr(column string, expression interface{}) *Session {
	s := e.NewSession()
	s.autoClose = true
	return s.SetExpr(column, expression)
}

// Table temporarily change the Get, Find, Update's table
func (e *Engine) Table(tableNameOrBean interface{}) *Session {
	s := e.NewSession()
	s.autoClose = true
	return s.Table(tableNameOrBean)
}

// Alias set the table alias
func (e *Engine) Alias(alias string) *Session {
	s := e.NewSession()
	s.autoClose = true
	return s.Alias(alias)
}

// Limit will generate "LIMIT start, limit"
func (e *Engine) Limit(limit int, start ...int) *Session {
	s := e.NewSession()
	s.autoClose = true
	return s.Limit(limit, start...)
}

// Desc will generate "ORDER BY column1 DESC, column2 DESC"
func (e *Engine) Desc(colNames ...string) *Session {
	s := e.NewSession()
	s.autoClose = true
	return s.Desc(colNames...)
}

// Asc will generate "ORDER BY column1,column2 Asc"
// This method can chainable use.
//
//        engine.Desc("name").Asc("age").Find(&users)
//        // SELECT * FROM user ORDER BY name DESC, age ASC
//
func (e *Engine) Asc(colNames ...string) *Session {
	s := e.NewSession()
	s.autoClose = true
	return s.Asc(colNames...)
}

// OrderBy will generate "ORDER BY order"
func (e *Engine) OrderBy(order string) *Session {
	s := e.NewSession()
	s.autoClose = true
	return s.OrderBy(order)
}

// Prepare 启用准备语句。
func (e *Engine) Prepare() *Session {
	s := e.NewSession()
	s.autoClose = true
	return s.Prepare()
}

// Join the join_operator should be one of INNER, LEFT OUTER, CROSS etc - this will be prepended to JOIN
func (e *Engine) Join(joinOperator string, tablename interface{}, condition string, args ...interface{}) *Session {
	s := e.NewSession()
	s.autoClose = true
	return s.Join(joinOperator, tablename, condition, args...)
}

// GroupBy generate group by statement
func (e *Engine) GroupBy(keys string) *Session {
	s := e.NewSession()
	s.autoClose = true
	return s.GroupBy(keys)
}

// Having generate having statement
func (e *Engine) Having(conditions string) *Session {
	s := e.NewSession()
	s.autoClose = true
	return s.Having(conditions)
}

// Table table struct
type Table struct {
	*schema.Table
	Name string
}

// IsValid if table is valid
func (t *Table) IsValid() bool {
	return t.Table != nil && len(t.Name) > 0
}

// TableInfo get table info according to bean's content
func (e *Engine) TableInfo(bean interface{}) (*schema.Table, error) {
	v := utils.ReflectValue(bean)
	return e.tagParser.ParseWithCache(v)
}

// IsTableEmpty if a table has any reocrd
func (e *Engine) IsTableEmpty(bean interface{}) (bool, error) {
	s := e.NewSession()
	defer s.Close()
	return s.IsTableEmpty(bean)
}

// IsTableExist if a table is exist
func (e *Engine) IsTableExist(beanOrTableName interface{}) (bool, error) {
	s := e.NewSession()
	defer s.Close()
	return s.IsTableExist(beanOrTableName)
}

// GetTable TableName 的别名，获取表名。
func (e *Engine) GetTable(bean interface{}, includeSchema ...bool) string {
	return dialect.FullTableName(e.dialect, e.GetTableMapper(), bean, includeSchema...)
}

// TableName returns table name with schema prefix if has
func (e *Engine) TableName(bean interface{}, includeSchema ...bool) string{
	return e.GetTable(bean,includeSchema...)
}

// CreateIndexes create indexes
func (e *Engine) CreateIndexes(bean interface{}) error {
	s := e.NewSession()
	defer s.Close()
	return s.CreateIndexes(bean)
}

// CreateUniques create uniques
func (e *Engine) CreateUniques(bean interface{}) error {
	s := e.NewSession()
	defer s.Close()
	return s.CreateUniques(bean)
}

// ClearCacheBean if enabled cache, clear the cache bean
func (e *Engine) ClearCacheBean(bean interface{}, id string) error {
	tableName := dialect.FullTableName(e.dialect, e.GetTableMapper(), bean)
	cacher := e.GetICache(tableName)
	if cacher != nil {
		cacher.ClearIds(tableName)
		cacher.DelBean(tableName, id)
	}
	return nil
}

// ClearCache if enabled cache, clear some tables' cache
func (e *Engine) ClearCache(beans ...interface{}) error {
	for _, bean := range beans {
		tableName := dialect.FullTableName(e.dialect, e.GetTableMapper(), bean)
		cacher := e.GetICache(tableName)
		if cacher != nil {
			cacher.ClearIds(tableName)
			cacher.ClearBeans(tableName)
		}
	}
	return nil
}

// UnMapType remove table from tables cache
func (e *Engine) UnMapType(t reflect.Type) {
	e.tagParser.ClearCacheTable(t)
}

// Sync the new struct changes to database, this method will automatically add
// table, column, index, unique. but will not delete or change anything.
// If you change some field, you should change the database manually.
func (e *Engine) Sync(beans ...interface{}) error {
	session := e.NewSession()
	defer session.Close()

	for _, bean := range beans {
		v := utils.ReflectValue(bean)
		tableNameNoSchema := dialect.FullTableName(e.dialect, e.GetTableMapper(), bean)
		table, err := e.tagParser.ParseWithCache(v)
		if err != nil {
			return err
		}

		isExist, err := session.Table(bean).isTableExist(tableNameNoSchema)
		if err != nil {
			return err
		}
		if !isExist {
			err = session.createTable(bean)
			if err != nil {
				return err
			}
		}
		/*isEmpty, err := engine.IsEmptyTable(bean)
		  if err != nil {
		      return err
		  }*/
		var isEmpty bool
		if isEmpty {
			err = session.dropTable(bean)
			if err != nil {
				return err
			}
			err = session.createTable(bean)
			if err != nil {
				return err
			}
		} else {
			for _, col := range table.Columns() {
				isExist, err := e.dialect.IsColumnExist(e.db, session.ctx, tableNameNoSchema, col.Name)
				if err != nil {
					return err
				}
				if !isExist {
					if err := session.statement.SetRefBean(bean); err != nil {
						return err
					}
					err = session.addColumn(col.Name)
					if err != nil {
						return err
					}
				}
			}

			for name, index := range table.Indexes {
				if err := session.statement.SetRefBean(bean); err != nil {
					return err
				}
				if index.Type == schema.UniqueType {
					isExist, err := session.isIndexExist2(tableNameNoSchema, index.Cols, true)
					if err != nil {
						return err
					}
					if !isExist {
						if err := session.statement.SetRefBean(bean); err != nil {
							return err
						}

						err = session.addUnique(tableNameNoSchema, name)
						if err != nil {
							return err
						}
					}
				} else if index.Type == schema.IndexType {
					isExist, err := session.isIndexExist2(tableNameNoSchema, index.Cols, false)
					if err != nil {
						return err
					}
					if !isExist {
						if err := session.statement.SetRefBean(bean); err != nil {
							return err
						}

						err = session.addIndex(tableNameNoSchema, name)
						if err != nil {
							return err
						}
					}
				} else {
					return errors.New("unknow index type")
				}
			}
		}
	}
	return nil
}

// Sync2 synchronize structs to database tables
func (e *Engine) Sync2(beans ...interface{}) error {
	s := e.NewSession()
	defer s.Close()
	return s.Sync2(beans...)
}

// Create (CreateTables) 根据bean创建多张表。
func (e *Engine) Create(beans ...interface{}) error {
	s := e.NewSession()
	defer s.Close()

	err := s.Begin()
	if err != nil {
		return err
	}

	for _, bean := range beans {
		err = s.createTable(bean)
		if err != nil {
			s.Rollback()
			return err
		}
	}
	return s.Commit()
}

// Drop (DropTables) 删除多张指定的表。
func (e *Engine) Drop(beans ...interface{}) error {
	s := e.NewSession()
	defer s.Close()

	err := s.Begin()
	if err != nil {
		return err
	}

	for _, bean := range beans {
		err = s.dropTable(bean)
		if err != nil {
			s.Rollback()
			return err
		}
	}
	return s.Commit()
}

// DropIndexes drop indexes of a table
func (e *Engine) DropIndexes(bean interface{}) error {
	s := e.NewSession()
	defer s.Close()
	return s.DropIndexes(bean)
}

// Exec raw sql
func (e *Engine) Exec(sqlOrArgs ...interface{}) (sql.Result, error) {
	s := e.NewSession()
	defer s.Close()
	return s.Exec(sqlOrArgs...)
}

// Query a raw sql and return records as []map[string][]byte
func (e *Engine) QueryBytes(sqlOrArgs ...interface{}) (resultsSlice []map[string][]byte, err error) {
	s := e.NewSession()
	defer s.Close()
	return s.QueryBytes(sqlOrArgs...)
}

// Query a raw sql and return records as []map[string]Value
func (e *Engine) QueryValue(sqlOrArgs ...interface{}) (resultsSlice []map[string]Value, err error) {
	s := e.NewSession()
	defer s.Close()
	return s.QueryValue(sqlOrArgs...)
}

// Query a raw sql and return records as Result
func (e *Engine) QueryResult(sqlOrArgs ...interface{}) (result *ResultValue) {
	s := e.NewSession()
	defer s.Close()
	return s.QueryResult(sqlOrArgs...)
}

// QueryStr (QueryString) runs a raw sql and return records as []map[string]string
func (e *Engine) QueryStr(sqlOrArgs ...interface{}) ([]map[string]string, error) {
	s := e.NewSession()
	defer s.Close()
	return s.QueryStr(sqlOrArgs...)
}

// QueryInterface runs a raw sql and return records as []map[string]interface{}
func (e *Engine) QueryInterface(sqlOrArgs ...interface{}) ([]map[string]interface{}, error) {
	s := e.NewSession()
	defer s.Close()
	return s.QueryInterface(sqlOrArgs...)
}

// Insert one or more records
func (e *Engine) Insert(beans ...interface{}) (int64, error) {
	s := e.NewSession()
	defer s.Close()
	return s.Insert(beans...)
}

// InsertOne insert only one record
func (e *Engine) InsertOne(bean interface{}) (int64, error) {
	s := e.NewSession()
	defer s.Close()
	return s.InsertOne(bean)
}

// Update records, bean's non-empty fields are updated contents,
// condiBean' non-empty filds are conditions
// CAUTION:
//        1.bool will defaultly be updated content nor conditions
//         You should call UseBool if you have bool to use.
//        2.float32 & float64 may be not inexact as conditions
func (e *Engine) Update(bean interface{}, condiBeans ...interface{}) (int64, error) {
	s := e.NewSession()
	defer s.Close()
	return s.Update(bean, condiBeans...)
}

// Delete records, bean's non-empty fields are conditions
func (e *Engine) Delete(bean interface{}) (int64, error) {
	s := e.NewSession()
	defer s.Close()
	return s.Delete(bean)
}

// Get retrieve one record from table, bean's non-empty fields
// are conditions
func (e *Engine) Take (bean interface{}) (bool, error) {
	s := e.NewSession()
	defer s.Close()
	return s.Take(bean)
}

// Exist returns true if the record exist otherwise return false
func (e *Engine) Exist(bean ...interface{}) (bool, error) {
	s := e.NewSession()
	defer s.Close()
	return s.Exist(bean...)
}

// Find retrieve records from table, condiBeans's non-empty fields
// are conditions. beans could be []Struct, []*Struct, map[int64]Struct
// map[int64]*Struct
func (e *Engine) Find(beans interface{}, condiBeans ...interface{}) error {
	s := e.NewSession()
	defer s.Close()
	return s.Find(beans, condiBeans...)
}

// FindAndCount find the results and also return the counts
func (e *Engine) FindAndCount(rowsSlicePtr interface{}, condiBean ...interface{}) (int64, error) {
	s := e.NewSession()
	defer s.Close()
	return s.FindAndCount(rowsSlicePtr, condiBean...)
}

// Iterate record by record handle records from table, bean's non-empty fields
// are conditions.
func (e *Engine) Iterate(bean interface{}, fun IterFunc) error {
	s := e.NewSession()
	defer s.Close()
	return s.Iterate(bean, fun)
}

// Rows return sql.Rows compatible Rows obj, as a forward Iterator object for iterating record by record, bean's non-empty fields
// are conditions.
func (e *Engine) Rows(bean interface{}) (*Rows, error) {
	s := e.NewSession()
	return s.Rows(bean)
}

// Count counts the records. bean's non-empty fields are conditions.
func (e *Engine) Count(bean ...interface{}) (int64, error) {
	s := e.NewSession()
	defer s.Close()
	return s.Count(bean...)
}

// Sum sum the records by some column. bean's non-empty fields are conditions.
func (e *Engine) Sum(bean interface{}, colName string) (float64, error) {
	s := e.NewSession()
	defer s.Close()
	return s.Sum(bean, colName)
}

// SumInt sum the records by some column. bean's non-empty fields are conditions.
func (e *Engine) SumInt(bean interface{}, colName string) (int64, error) {
	s := e.NewSession()
	defer s.Close()
	return s.SumInt(bean, colName)
}

// Sums sum the records by some columns. bean's non-empty fields are conditions.
func (e *Engine) Sums(bean interface{}, colNames ...string) ([]float64, error) {
	s := e.NewSession()
	defer s.Close()
	return s.Sums(bean, colNames...)
}

// SumsInt like Sums but return slice of int64 instead of float64.
func (e *Engine) SumsInt(bean interface{}, colNames ...string) ([]int64, error) {
	s := e.NewSession()
	defer s.Close()
	return s.SumsInt(bean, colNames...)
}

// ImportFile SQL DDL file
func (e *Engine) ImportFile(ddlPath string) ([]sql.Result, error) {
	s := e.NewSession()
	defer s.Close()
	return s.ImportFile(ddlPath)
}

// Import SQL DDL from io.Reader
func (e *Engine) Import(r io.Reader) ([]sql.Result, error) {
	s := e.NewSession()
	defer s.Close()
	return s.Import(r)
}

// nowTime return current time
func (e *Engine) nowTime(col *schema.Column) (interface{}, time.Time) {
	t := time.Now()
	var tz = e.DatabaseTZ
	if !col.DisableTimeZone && col.TimeZone != nil {
		tz = col.TimeZone
	}
	return dialect.FormatTime(e.dialect, col.SQLType.Name, t.In(tz)), t.In(e.TZLocation)
}

// GetColumnMapper returns the column name mapper
func (e *Engine) GetColumnMapper() mapper.IMapper {
	return e.tagParser.GetColumnMapper()
}

// GetTableMapper returns the table name mapper
func (e *Engine) GetTableMapper() mapper.IMapper {
	return e.tagParser.GetTableMapper()
}

// GetTZLocation returns time zone of the application
func (e *Engine) GetTZLocation() *time.Location {
	return e.TZLocation
}

// SetTZLocation sets time zone of the application
func (e *Engine) SetTZLocation(tz *time.Location) {
	e.TZLocation = tz
}

// GetTZDatabase returns time zone of the database
func (e *Engine) GetTZDatabase() *time.Location {
	return e.DatabaseTZ
}

// SetTZDatabase sets time zone of the database
func (e *Engine) SetTZDatabase(tz *time.Location) {
	e.DatabaseTZ = tz
}

// SetSchema sets the schema of database
func (e *Engine) SetSchema(schema string) {
	e.dialect.URI().SetSchema(schema)
}

func (e *Engine) AddHook(hook ictx.IHook) {
	e.db.AddHook(hook)
}

// Unscoped always disable struct tag "deleted"
func (e *Engine) Unscoped() *Session {
	s := e.NewSession()
	s.autoClose = true
	return s.Unscoped()
}

func (e *Engine) tbNameWithSchema(v string) string {
	return dialect.TableNameWithSchema(e.dialect, v)
}

// ContextHook creates a session with the context
func (e *Engine) Context(ctx context.Context) *Session {
	s := e.NewSession()
	s.autoClose = true
	return s.Context(ctx)
}

// SetDefaultContext set the default context
func (e *Engine) SetDefaultContext(ctx context.Context) {
	e.ctx = ctx
}

// PingCtx (PingContext) tests if database is alive
func (e *Engine) PingCtx(ctx context.Context) error {
	s := e.NewSession()
	defer s.Close()
	return s.PingCtx(ctx)
}

// Transaction Execute sql wrapped in a transaction(abbr as tx), tx will automatic commit if no errors occurred
func (e *Engine) Tx(f func(*Session) (interface{}, error)) (interface{}, error) {
	s := e.NewSession()
	defer s.Close()

	if err := s.Begin(); err != nil {
		return nil, err
	}

	result, err := f(s)
	if err != nil {
		return result, err
	}

	if err := s.Commit(); err != nil {
		return result, err
	}

	return result, nil
}
